import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
    state:{
        goodsList:localStorage.getItem('goodslist')?JSON.parse(localStorage.getItem('goodslist')):[],
        userInfo:[
            {
                username:'zhangsan',
                password:"123"
            },
            {
                username:'lisi',
                password:"456"
            },
            {
                username:'sxx',
                password:"666"
            }
        ],
        myCartGoods:localStorage.getItem('myCart')?JSON.parse(localStorage.getItem('myCart')):[]
    },
    mutations:{
        ADD_GOODS(state,value){
            state.goodsList = [
                ...state.goodsList,
                value
            ];
            localStorage.setItem('goodslist',JSON.stringify(state.goodsList));
        },
        ADD_TO_MY_CART(state,value){
            let flag = false;
            state.myCartGoods.forEach(item=>{
                if(item.id === value.id){
                    if(item.productStock <= item.num){
                        alert('库存不足');
                    }else {
                        item.num++;
                    }
                    //购物车中存在
                    flag = true;
                }
            })
            if(!flag){
                state.myCartGoods = [
                    ...state.myCartGoods,
                    {
                        ...value,
                        num:1
                    }
                ]
            }
            localStorage.setItem('myCart',JSON.stringify(state.myCartGoods));
        },
        REDUCE_NUM(state,obj){
            if(obj.num === 1){
                if(window.confirm('确认删除当前商品吗?')){
                    state.myCartGoods = state.myCartGoods.filter(item=>{
                        return item.id !== obj.id;
                    })
                }
            }else {
                state.myCartGoods = state.myCartGoods.map(item=>{
                    if(item.id === obj.id){
                        item.num--;
                    }
                    return item;
                });
            }
            localStorage.setItem('myCart',JSON.stringify(state.myCartGoods));
        }
    },
    getters:{
        total(state){
            return state.myCartGoods.reduce((sum,item)=>{
                sum+=item.productPrice*item.num;
                return sum;
            },0)
        }
    }
})
export default store;